var flag = false;
var gradeArray = new Array();
gradeArray[1]="☆";
gradeArray[2]="★";
gradeArray[3]="★☆";
gradeArray[4]="★★";
gradeArray[5]="★★☆";
gradeArray[6]="★★★";
gradeArray[7]="★★★☆";
gradeArray[8]="★★★★";
gradeArray[9]="★★★★☆";
gradeArray[10]="★★★★★";
var FlowProjectModule = function () {

	$('#btn_reset').click(function(){
		$('#urls').val('');
	});
	
    var editable = function () {
        return {
            init: function () {
                var oTable = $('#modelEditable').dataTable({
                    "lengthMenu": [
                        [10, 15, 20, 50],
                        [10, 15, 20, 50]
                    ],
                    "autoWidth":false,
                    "displayLength": 10,
                    "scrollX": true,
                    "language": {
                        "lengthMenu": "每页 _MENU_ 条记录",
                        "paginate": {
                            "previous": "上一页",
                            "next": "下一页"
                        },
                        "info" : "从 _START_ 到  _END_ 条，总记录为 _TOTAL_ 条",    
                        "infoEmpty" : "记录数为0",
                    },
                    "columnDefs": [
						{
						    "data": null,
						    'sortable': false,
						    "defaultContent": "<center>-</center>",
						    "targets": [0]
						},
						{
						    "data": null,
						    'sortable': false,
						    "defaultContent": "<center>-</center>",
						    "targets": [1]
						}, 
						{
						    "data": null,
						    'sortable': false,
						    "defaultContent": "<center>-</center>",
						    "targets": [2]
						}, 
						{
						    "data": null,
						    'sortable': false,
						    "defaultContent": "<center>-</center>",
						    "targets": [3]
						}, 
						{
						    "data": null,
						    'sortable': false,
						    "defaultContent": "<center>-</center>",
						    "targets": [4]
						}, 
						{
						    "data": null,
						    'sortable': false,
						    "defaultContent": "<center>-</center>",
						    "targets": [5]
						}, 
						{
						    "data": null,
						    'sortable': false,
						    "defaultContent": "-",
						    "targets": [6]
						}, 
						{
						    "data": null,
						    'sortable': false,
						    "defaultContent": "-",
						    "targets": [7]
						}, 
						{
						    "data": null,
						    'sortable': false,
						    "defaultContent": "-",
						    "targets": [8]
						}, 
						{
						    "data": null,
						    'sortable': false,
						    "defaultContent": "-",
						    "targets": [9]
						}
                    ],
                    "columns": [
                       { "data": "code" },
                       { "data": "name" },
                       { "data": "type" },
                       { "data": "enterpriseName" },
                       { "data": "amount" },
                       { "data": "amountInvested" },
                       { "data": "createTime" },
                       { "data": "stateType" },
                       { "data": "grade" },
                       { "data": "operter" }
                   ],
                   "filter" : false,
                   "processing": false,
                   "serverSide": true,
                   "ajaxSource": ctx + "/project/queryStoreProject",
                   "serverMethod": "post",
                   "fnRowCallback" : function(nRow, aData, displayIndex) {
                	   nRow.children[0].id = aData.id;
                	   nRow.children[0].name = aData.name;
                	   var type = aData.type;
                	   if (type == '1') {
                		   $('td:eq(2)', nRow).html('债券');
                	   }else if(type == '2'){
                		   $('td:eq(2)', nRow).html('股权');
                	   }
                	   var enterpriseName = aData.enterpriseName;
                	   var smallEName = enterpriseName.substr(0, 20);
                	   if(enterpriseName.length >20){
                		   $('td:eq(3)', nRow).html("<p title="+clearBr(enterpriseName)+">"+smallEName+'......</p>');
                	   }
                	   var name = aData.name;
                	   var smallName = name.substr(0, 20);
                	   if(name.length >20){
                		   $('td:eq(1)', nRow).html("<p title="+clearBr(name)+">"+smallName+'......</p>');
                	   }
                	   $('td:eq(4)', nRow).html(formatCurrency(aData.amount));
                	   var createTime = aData.createTime;
                	   $('td:eq(6)', nRow).html(createTime.substring(0,10));gradeArray
                	   $('td:eq(8)', nRow).html(gradeArray[aData.grade]);
                	   var operater = '<a class="detail fa fa-bars fa-lg " title="查看" href="javascript:;"></a>&nbsp;&nbsp;&nbsp;<a class="modify fa fa-pencil fa-lg" title="修改" href="javascript:;"></a>&nbsp;&nbsp;&nbsp;<a class="grade fa fa-font fa-lg" title="评级" href="javascript:;"></a>&nbsp;&nbsp;&nbsp;<a class="contract fa fa-file-text-o fa-lg" title="合同" href="javascript:;"></a>';
                	   if(aData.operter!= null){
                		   operater = operater + aData.operter;
                	   }
                	   $('td:eq(9)', nRow).html(operater);
                       return nRow;
                   },
                   "fnServerData" : function(ajaxSource, dataSet, fnCallback) {
	                   var json = "";
	                   var s;
	                   for (var i = 0; i < dataSet.length; i++) {
	                       s = dataSet[i];
	                   	   if (s.name == 'sEcho') {
	                   		   json = json + '"echo":' + s.value;
		                   } else if (s.name == 'iDisplayStart') {
		                	   json = json + ',"start":' + s.value;
		                   } else if (s.name == 'iDisplayLength') {
		                	   json = json + ',"pageSize":' + s.value;
		                   }
	                   }
            	       var form = $("form#queryForm").serializeJSON();
                   	   var js = form.replace('}', ',');
                   	   json = js + json + "}";
                       $.ajax({
                       	   "contentType":"application/json; charset=UTF-8",
                           "dataType" : 'json',
                           "type" : "POST",
                           "url" : ctx + "/project/queryStoreProject",
                           "data" : json,
                           "success" : fnCallback
                       });
                   },
                });
                //查看项目
                $('#modelEditable').on("click", "a.detail", (function (e) {
                    e.preventDefault();
                    var nRow = $(this).parents('tr')[0];
                    var id = nRow.children[0].id;
                    window.location.href = ctx +"/project/detail/"+id;
                    return;
                }));
                //修改项目
                $('#modelEditable').on("click", "a.modify", (function (e) {
                    e.preventDefault();
                    var nRow = $(this).parents('tr')[0];
                    var id = nRow.children[0].id;
                    window.location.href = ctx +"/project/edit/"+id;
                    return;
                }));
                //评级
                $('#modelEditable').on("click", "a.grade", (function (e) {
                    e.preventDefault();
                    var nRow = $(this).parents('tr')[0];
                    var id = nRow.children[0].id;
                    var name = nRow.children[0].name;
                    $("#project_event_id").val(id);
                    $("#report_grade").click();
                }));
                //合同
                $('#modelEditable').on("click", "a.contract", (function (e) {
                    e.preventDefault();
                    var nRow = $(this).parents('tr')[0];
                    var id = nRow.children[0].id;
                    var name = nRow.children[0].name;
                    $("#report_project_eventId").val(id);
                    $("#report").click();
                    oTable1.fnClearTable();
                }));
                
                $('#btn_query').click(function(){
                	oTable.fnClearTable();
                });
            }

        };
    }();
    return {
        init: function () {
        	editable.init();
        	
        }
    };
}();


var ProjectReport = function() {
	var editable1 = function() {

		return {
			init : function() {
				oTable1 = $('#modelEditable_report').dataTable(
								{
									"autoWidth" : false,
									"lengthMenu" : [ [ 10, 15, 20, 50, -1 ],
											[ 10, 15, 20, 50, "All" ] ],
									"displayLength" : -1,
									"language" : {
										"lengthMenu" : "每页 _MENU_ 条记录",
										"paginate" : {
											"previous" : "上一页",
											"next" : "下一页"
										},
										"info" : "",// "从 _START_ 到 _END_ 条，总记录为
													// _TOTAL_ 条",
										"infoEmpty" : "",// 记录数为0",
										"sZeroRecords" : "找不到相关数据"
									},
									"bPaginate" : false, // 是否显示分页
									"bLengthChange" : false, // 每页显示的记录数
									"columnDefs" : [ {
										"data" : null,
										"sortable" : false,
										"defaultContent" : "<center>-</center>",
										"targets" : [ 0 ]
									}, {
										"data" : null,
										"sortable" : false,
										"defaultContent" : "<center>-</center>",
										"targets" : [ 1 ]
									}, {
										"data" : null,
										"sortable" : false,
										"defaultContent" : "<center>-</center>",
										"targets" : [ 2 ]
									}, {
										"data" : null,
										"sortable" : false,
										"defaultContent" : "<center>-</center>",
										"targets" : [ 3 ]
									} ],
									"columns" : [ {
										"data" : "contractName"
									}, {
										"data" : "employeeName"
									}, {
										"data" : "createTime"
									}, {
										"data" : "operater"
									}],
									"filter" : false,
									"processing" : false,
									"serverSide" : true,
									"ajaxSource" : ctx
											+ "/project/projectReport",
									"serverMethod" : "post",
									"fnRowCallback" : function(nRow, aData,displayIndex) {
										nRow.children[0].id = aData.id;
										nRow.children[0].name = aData.contractName;
										var roleType = aData.roleType
										var roleName ="";
										$('td:eq(3)', nRow).html('<a class="delete fa fa-trash-o fa-lg " title="移除" href="javascript:;"></a>&nbsp;&nbsp;&nbsp;<a class="modify fa fa-cog fa-lg " title="重命名" href="javascript:;"></a>');
										return nRow;
									},
									"fnServerData" : function(ajaxSource,dataSet, fnCallback) {
										var start;
										var pageSize;
										for (var i = 0; i < dataSet.length; i++) {
											s = dataSet[i];
											if (s.name == 'iDisplayStart') {
												start = s.value;
											} else if (s.name == 'iDisplayLength') {
												pageSize = s.value;
											}
										}
										var id = $("#report_project_eventId").val();
										$.ajax({
													"contentType" : "application/json; charset=UTF-8",
													"dataType" : 'json',
													"type" : "POST",
													"url" : ajaxSource,
													"data" : '{"projectId":"'
															+ $("#report_project_eventId").val()
															+ '","start":'
															+ start
															+ ',"type":'
															+ 3
															+ ',"pageSize":'
															+ pageSize + "}",
													"success" : fnCallback
												});
									},
								});
							 //移除合同文件
			                $('#modelEditable_report').on("click", "a.delete", (function (e) {
			                    e.preventDefault();
			                    var nRow = $(this).parents('tr')[0];
			                    var id = nRow.children[0].id;
			                    var name = nRow.children[0].name;
			                    $.teninedialog({
			                	    title:'系统提示',
			                	    content:'确认移除['+name+']合同文件吗?',
			                	    showCloseButton:false,
			                	    otherButtons:["确定","取消"],
			                	    otherButtonStyles:['btn-primary','btn-white'],
			                	    bootstrapModalOption:{keyboard: true},
			                	    clickButton:function(sender,modal,index){
			                	   	 //移除文件
			                	   	 if(index == 0){
			                	   		var json = "{\"id\":\""+id+"\"}";
			                	   		$.ajax({
			                	   	      	  type:"post",
			                	   	          contentType:"application/json; charset=UTF-8",
			                	   	          url: ctx + "/projectAttachment/delete/"+id,
			                	   	          dataType:"json",
			                	   	          success: function(msg){
			                	   	        	  oTable1.fnClearTable();
			                	   	          },
			                	   	          error: function (msg) {
			                	   	          	bootbox.alert(msg.message);
			                	   	          }
			                	   	      });
			                	   	 }
			                	   	 $(this).closeDialog(modal); 
			                	    }
			                	});
			                    return;
			                }));
			                //重命名合同文件
			                $('#modelEditable_report').on("click", "a.modify", (function (e) {
			                    e.preventDefault();
			                    var nRow = $(this).parents('tr')[0];
			                    var id = nRow.children[0].id;
			                    var name = nRow.children[0].name;
			                    $("#project_attachment_id").val(id);
			                    $("#old_file_name").html(name);
			                    $("#report_rename").click();
			                    $("#modify_file_name").val("");
			                    oTable1.fnClearTable(); 
			                    return;
			                }));
				

			}

		};

	}();

	return {
		init : function() {
			editable1.init();
		}
	};
}();

$("#btn_rename_project_attachment").click(function(){
	var file_name = $('#modify_file_name').val();
	var size = file_name.length;
	var old_name = $('#old_file_name').html();
	var id = $('#project_attachment_id').val();
	if(size >10 || size <=0){
		bootbox.alert("文件名长度长度需在1到10个字符之间");
		return;
	}
	if(file_name == old_name){
		bootbox.alert("新名称与旧名称相同");
		return;
	}
	json = "{\"id\":\""+id+"\",\"contractName\":\""+file_name+"\"}";
    var str = json;
    $.ajax({
    	type:"post",
        contentType:"application/json; charset=UTF-8",
        url: ctx + "/projectAttachment/rename",
        data:json,
        dataType:"json",
        success: function(msg){
        	$("#dsimiss_rename_contract").click();
        	oTable1.fnClearTable();
        },
        error: function (msg) {
        	bootbox.alert(msg.message);
        }
    });
});

//上传合同
function uploadReportFile(){
	if(!$("#contractFile").val()){
		bootbox.alert("请先添加合同文件！");
		return;
	}
	 $.ajaxFileUpload({
            url: ctx + '/projectAttachment/uploadContractFile',
            type: 'post',
            secureuri: false,
            fileElementId: 'contractFile',
            dataType: 'json',
            data:{'projectId': $("#report_project_eventId").val(),'type':3},
            success: function(data, status){
            	if (data.code == 1) {
            		bootbox.dialog({
    					message : "上传成功！ ",
    					title : "温馨提示：",
    					buttons : {
    						main : {
    							label : "确定",
    							className : "btn btn-outline btn-primary",
    							callback : function() {
    								oTable1.fnClearTable();
    							}
    						}
    					}
    				});
            		
            	} else {
            		bootbox.alert(data.message);
            	}
            },
            error: function(msg, status, e){
            	bootbox.alert("上传失败！");
            }
        });
} 

//项目评级
$("#btn_grade_project_attachment").click(function (){
	if(!$("#relatedFile").val()){
		bootbox.alert("请先添加评级文件！");
		return;
	}
	 $.ajaxFileUpload({
            url: ctx + '/projectAttachment/uploadRelatedFile',
            type: 'post',
            secureuri: false,
            fileElementId: 'relatedFile',
            dataType: 'json',
            data:{'projectId': $("#project_event_id").val(),'type':4,'grade':$("#grade").val()},
            success: function(data, status){
            	if (data.code == 1) {
            		bootbox.dialog({
    					message : "上传成功！ ",
    					title : "温馨提示：",
    					buttons : {
    						main : {
    							label : "确定",
    							className : "btn btn-outline btn-primary",
    							callback : function() {
    								location.reload();
    							}
    						}
    					}
    				});
            	} else {
            		bootbox.alert(data.message);
            	}
            },
            error: function(msg, status, e){
            	bootbox.alert("上传失败！");
            }
        });
});

/** 
 * 将数值四舍五入(保留2位小数)后格式化成金额形式 
 * @param num 数值(Number或者String) 
 * @return 金额格式的字符串
 * @type String 
 */  
function formatCurrency(num) {  
    num = num.toString().replace(/\$|\,/g,'');  
    if(isNaN(num))  
        num = "0";  
    sign = (num == (num = Math.abs(num)));  
    num = Math.floor(num*100+0.50000000001);  
    cents = num%100;  
    num = Math.floor(num/100).toString();  
    if(cents<10)  
    cents = "0" + cents;  
    for (var i = 0; i < Math.floor((num.length-(1+i))/3); i++)  
    num = num.substring(0,num.length-(4*i+3))+','+  
    num.substring(num.length-(4*i+3));  
    return (((sign)?'':'-') + num + '.' + cents);  
}  

//去除换行、空格
function clearBr(key)
{
	key = key.replace(/\s+/g, "");	
    key = key.replace(/<\/?.+?>/g,"");
    key = key.replace(/[\r\n]/g, "");
    return key;
}